package com.example.controller;

import com.example.utils.PersonalTool;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class FileController {

    private static final String UPLOAD_DIR = "webapps/uploads";

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file, Model model) {
        String message;
        if (file.isEmpty()) {
            message = "上传失败，请选择文件";
        } else {
            try {
                // 获取文件名
                String fileName = file.getOriginalFilename();
                // 创建上传目录
                File uploadDir = new File(UPLOAD_DIR);
                message = "初始化";
                if (!uploadDir.exists()) {
                    boolean created = uploadDir.mkdirs();
                    message =  "创建目录结果：" + created;
                    System.out.println("创建目录结果：" + created);
                }
                // 构建文件保存路径
                Path filePath = Paths.get(UPLOAD_DIR, fileName);
                // /usr/local/tomcat/uploads/demo.png
                System.out.println("实际文件保存路径: " + filePath.toAbsolutePath()); // 添加这行代码
                // 保存文件
                Files.write(filePath, file.getBytes());
                //message = "上传成功";
                message = "实际文件保存路径: " + filePath.toAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
                message = "上传失败：" + e.getMessage();
            }
        }
        // 将结果信息添加到模型中
        model.addAttribute("message", message);
        // 返回视图名称
        return "uploadResult";
    }

}